use sqlx::SqlitePool;
use tokio_cron_scheduler::{Job, JobScheduler};
use tracing::{info, error};
use crate::config::Config;
use crate::services::{PlanService, WeChatService};
use crate::utils::MessageCache;

/// 启动提醒调度器
pub async fn start_reminder_scheduler(
    pool: SqlitePool,
    config: Config,
    msg_cache: MessageCache,
) -> anyhow::Result<()> {
    info!("Starting reminder scheduler...");
    
    let scheduler = JobScheduler::new().await?;
    
    // 任务1: 每3分钟检查提醒
    let reminder_job = Job::new_async("0 */3 * * * *", move |_uuid, _lock| {
        let pool = pool.clone();
        let config = config.clone();
        
        Box::pin(async move {
            if let Err(e) = check_and_send_reminders(&pool, &config).await {
                error!("Failed to check reminders: {}", e);
            }
        })
    })?;
    
    // 任务2: 每10分钟清理过期缓存
    let cache_cleanup_job = Job::new_async("0 */10 * * * *", move |_uuid, _lock| {
        let cache = msg_cache.clone();
        
        Box::pin(async move {
            cache.cleanup_expired();
        })
    })?;
    
    scheduler.add(reminder_job).await?;
    scheduler.add(cache_cleanup_job).await?;
    scheduler.start().await?;
    
    info!("Reminder scheduler started successfully (with cache cleanup)");
    Ok(())
}

/// 检查并发送提醒
async fn check_and_send_reminders(pool: &SqlitePool, config: &Config) -> anyhow::Result<()> {
    info!("Checking for pending reminders...");
    
    // 查找所有待提醒的计划（包含用户名）
    let plans = PlanService::find_pending_reminders_with_user(pool).await?;
    
    if plans.is_empty() {
        info!("No pending reminders found");
        return Ok(());
    }
    
    info!("Found {} pending reminder(s)", plans.len());
    
    let wechat_service = WeChatService::new(config.wx_webhook_url.clone());
    
    for plan in plans {
        info!("Processing reminder for plan: id={}, name={}, user={}", plan.plan_id, plan.plan_name, plan.user_name);
        
        // 发送提醒（@ 用户）
        match wechat_service.send_reminder(&plan.user_name, &plan.description).await {
            Ok(_) => {
                info!("Reminder sent successfully for plan id={}", plan.plan_id);
                
                // 处理提醒后的更新
                if let Err(e) = PlanService::process_reminder(pool, plan.plan_id, &plan.frequency, plan.next_reminder).await {
                    error!("Failed to update plan after reminder: {}", e);
                }
            }
            Err(e) => {
                error!("Failed to send reminder for plan id={}: {}", plan.plan_id, e);
            }
        }
    }
    
    Ok(())
}
